<template>
    <el-dialog
        title="权限管控"
        :visible.sync="show"
        :before-close="handleCancel"
        :close-on-click-modal="false"
        width="600px"
    >
        <div v-loading="loadingGet1 || loadingGet2" v-if="reset">
            <div style="text-align:center;margin-top:-30px;">
                <el-radio-group v-model="authType" size="small">
                    <el-radio-button :label="1">系统权限</el-radio-button>
                    <el-radio-button :label="2">关联用户</el-radio-button>
                </el-radio-group>
            </div>
            <div v-show="authType===1">
                <el-checkbox-group v-model="checkList" style="margin-left:30px;margin-top:20px;">
                    <el-row>
                        <el-col :span="12" v-for="(item, index) in appList" :key="index">
                            <el-checkbox style="margin:10px;" :label="item.code">{{item.name}}</el-checkbox>
                            <el-button
                                :disabled="checkList.indexOf(item.code)<0"
                                type="text"
                                @click="onAuthDetail(item.code, item.name)"
                            >
                                <i class="el-icon-edit"></i>
                            </el-button>
                        </el-col>
                    </el-row>
                </el-checkbox-group>
            </div>
            <div v-show="authType===2">
                <table-ex
                    ref="tableExDest"
                    :queryCallback="queryCallbackDest"
                    :handleSelectionChange="onSelectionDestChange"
                    height="350"
                    style="margin-top:10px;"
                >
                    <el-table-column label="账号">
                        <template slot-scope="scope">
                            <div>
                                <strong
                                    style="margin-right:10px;"
                                    v-if="scope.row.loginName"
                                >{{scope.row.loginName}}</strong>
                                <el-tag
                                    size="small"
                                    v-if="scope.row.state == 1 && scope.row.effectTime == null"
                                    type="warning"
                                    :disable-transitions="true"
                                    effect="plain"
                                >未开户</el-tag>
                                <el-tag
                                    size="small"
                                    v-if="scope.row.state == 2"
                                    type="danger"
                                    :disable-transitions="true"
                                    effect="plain"
                                >禁用</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="用户姓名"></el-table-column>
                    <el-table-column label="操作" width="70">
                        <template slot-scope="scope">
                            <el-button
                                type="default"
                                size="mini"
                                class="button-in-cell"
                                @click="onRemoveUser(scope.row)"
                            >移除</el-button>
                        </template>
                    </el-table-column>
                </table-ex>
                <el-button
                    style="float:left;margin-top:12px;"
                    type="default"
                    @click="onShowAddUser"
                    size="mini"
                >添加用户</el-button>
            </div>
        </div>
        <div slot="footer" class="dialog-footer" style="clear:both;">
            <el-button @click="handleCancel" size="small">取消</el-button>
            <el-button type="primary" @click="handleSubmit" size="small" :loading="loadingSubmit">确定</el-button>
        </div>
        <el-drawer
            append-to-body
            :title="detailTitle"
            :visible.sync="drawer"
            direction="rtl"
            ref="drawer"
            :before-close="handleClose"
        >
            <!-- <div style="text-align:right;">
                <el-switch
                    v-model="relativeChecked"
                    active-text="关联选择">
                </el-switch>
            </div> -->
            <div ref="contentTree" v-loading="loadingDetail" class="scoped_1347">
                <el-tree
                    v-if="rerenderFlag"
                    ref="tree"
                    style="margin:10px;"
                    node-key="id"
                    highlight-current
                    :props="{
                        children: 'children',
                        label: 'name'
                    }"
                    :data="appDetailTree"
                    show-checkbox
                    default-expand-all
                    :check-strictly="!relativeChecked"
                    :expand-on-click-node="false"
                    :default-checked-keys="authMap[selAppCode]"
                    @check="onResIdCheck"
                    :render-content="renderContent"
                ></el-tree>
            </div>
        </el-drawer>
        <el-drawer
            append-to-body
            title="添加用户"
            :visible.sync="drawerSrc"
            direction="rtl"
            ref="drawerSrc"
            :before-close="handleCloseSrc"
        >
            <el-form :inline="true" :model="querySrcForm" style="margin-left:5px;" size="small">
                <el-form-item label>
                    <el-input v-model="querySrcForm.name" placeholder="姓名" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onQuerySrc" icon="el-icon-search">查询</el-button>
                </el-form-item>
            </el-form>
            <table-ex
                ref="tableExSrc"
                :queryCallback="queryCallbackSrc"
                :handleSelectionChange="onSelectionSrcChange"
                :sizeSel="false"
                :pageNum="false"
                style="padding:5px;"
            >
                <el-table-column label="账号">
                    <template slot-scope="scope">
                        <div>
                            <strong
                                style="margin-right:10px;"
                                v-if="scope.row.loginName"
                            >{{scope.row.loginName}}</strong>
                            <el-tag
                                size="small"
                                v-if="scope.row.state == 1 && scope.row.effectTime == null"
                                type="warning"
                                :disable-transitions="true"
                                effect="plain"
                            >未开户</el-tag>
                            <el-tag
                                size="small"
                                v-if="scope.row.state == 2"
                                type="danger"
                                :disable-transitions="true"
                                effect="plain"
                            >禁用</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="用户姓名"></el-table-column>
                <el-table-column label="操作" width="70">
                    <template slot-scope="scope">
                        <el-button
                            type="default"
                            size="mini"
                            class="button-in-cell"
                            @click="onAddUser(scope.row)"
                        >添加</el-button>
                    </template>
                </el-table-column>
            </table-ex>
        </el-drawer>
    </el-dialog>
</template>

<script>
import role_api from '../../api/role_api'
import sys_resource_api from '../../api/sys_resource_api'
import TableEx from '../../components/TableEx.vue'
export default {
    props: {
        id: Number,
        show: Boolean,
        success: Function,
        cancel: Function,
    },
    components: {
        TableEx,
    },
    watch: {
        show(val) {
            if (val) {
                this.reset = false
                this.$nextTick(() => {
                    Object.assign(this.$data, this.$options.data.call(this))
                    this.reset = true
                    this.init && this.init()
                })
            }
        },
        drawer(val) {
            if (val) {
                this.$nextTick(() => {
                    this.currentHoverItem = null
                    setTimeout(() => {
                        document.getElementsByClassName('el-drawer__header').forEach(e => e.children[0].blur())
                    }, 100)
                })
            }
        },
        drawerSrc(val) {
            if (val) {
                this.$nextTick(() => {
                    setTimeout(() => {
                        document.getElementsByClassName('el-drawer__header').forEach(e => e.children[0].blur())
                    }, 200)
                })
                if (this.$refs.tableExSrc) {
                    this.onQuerySrc(null, 1)
                }
            }
        }
    },
    data() {
        return {
            reset: true,
            drawer: false,
            drawerSrc: false,
            rules: {
                name: [
                    { required: true, message: '请输入角色名', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入角色唯一编码', trigger: 'blur' }
                ],
                description: [
                    {
                        type: 'string',
                        max: 100,
                        message: '不要超过100个字符',
                        trigger: 'blur'
                    }
                ]
            },
            detailTitle: '',
            loadingSubmit: false,
            loadingGet1: false,
            loadingGet2: false,
            authType: 1,
            appList: [],
            checkList: [],
            appAuthTree: {},
            appDetailTree: [],
            loadingDetail: false,
            authMap: {},
            selAppCode: null,
            selectedItems: [],
            selectedSrcItems: [],
            queryDestForm: {},
            querySrcForm: {},
            relativeChecked: false,
            dragCheckMap: {},
            currentHoverItem: null,
            rerenderFlag: true,
        }
    },
    methods: {
        init() {
            this.loadingGet2 = true
            role_api.appListWithAuth(this.id).then(data => {
                this.loadingGet2 = false
                this.appList = data
                this.checkList = this.appList.filter(e => e.authed).map(e => e.code)
            }).catch(err => {
                this.loadingGet2 = false
                this.$message.error(err.message)
            })
        },
        initAppData(appCode, appName) {
            this.detailTitle = appName
            if (!this.appAuthTree[appCode]) {
                this.loadingDetail = true
                role_api.appTreeDataWithAuth(this.id, appCode).then(data => {
                    this.appAuthTree[appCode] = data.children
                    this.appDetailTree = this.appAuthTree[appCode]
                    this.authMap[appCode] = this.treeToList(data.children)
                    this.loadingDetail = false
                }).catch(err => {
                    this.$message.error(err.message)
                    this.loadingDetail = false
                })
            } else {
                this.appDetailTree = this.appAuthTree[appCode]
            }
        },
        treeToList(tree) {
            let r = []
            tree.forEach(e => {
                if (e.authed) {
                    r.push(e.id)
                }
                if (e.children) {
                    r = r.concat(this.treeToList(e.children))
                }
            })
            return r
        },
        handleSubmit(callback) {
            this.loadingSubmit = true
            let postData = []
            this.checkList.forEach(e => {
                postData.push({
                    appCode: e,
                    resIdList: this.authMap[e]
                })
            })
            role_api.updateAuth(this.id, postData).then(data => {
                this.loadingSubmit = false
                this.$message.success('修改成功!')
                this.success()
            }).catch(err => {
                this.loadingSubmit = false
                this.$message.error(err.message)
            })
        },
        handleCancel() {
            this.cancel()
        },
        onAuthDetail(code, appName) {
            this.selAppCode = code
            this.initAppData(code, appName)
            this.drawer = true
        },
        handleClose(done) {
            done()
        },
        handleCloseSrc(done) {
            done()
        },
        onResIdCheck() {
            this.authMap[this.selAppCode] = this.$refs.tree.getCheckedKeys()
        },
        renderContent(h, { node, data, store }) {
            return (
                <span class="el-tree-node__label" style="width:88%;" onmouseover={
                    e=>{
                        this.currentHoverItem = data.id
                    }
                }>
                    <span>{node.label}</span>
                    {data.type === 2 ? <el-tag effect="plain" type="warning" size="mini" style="margin-left:5px;">菜单</el-tag> : ''}
                    {data.type === 3 ? <el-tag effect="plain" size="mini" style="margin-left:5px;">元素</el-tag> : ''}
                    <el-tag effect="plain" type="info" size="mini" style="margin-left:5px;">{data.code}</el-tag>
                    {this.currentHoverItem==data.id ? <div style="float:right;">
                        <el-button size="mini" icon="el-icon-top" class="up_down_icon_btn" circle onClick={e=>this.moveup(node, data.id)}></el-button>
                        <el-button size="mini" icon="el-icon-bottom" class="up_down_icon_btn" circle onClick={e=>this.movedown(node, data.id)}></el-button>
                    </div> : ''}
                </span>)
        },
        onQueryDest(event = null, type = 1) {
            this.$refs.tableExDest.refresh(type)
        },
        queryCallbackDest(param) {
            return role_api.destPageData({
                query: this.queryDestForm,
                ...param
            }, this.id)
        },
        onSelectionDestChange(items) {
            this.selectedDestItems = items
        },
        onQuerySrc(event = null, type = 1) {
            this.$refs.tableExSrc.refresh(type)
        },
        queryCallbackSrc(param) {
            return role_api.srcPageData({
                query: this.querySrcForm,
                ...param
            }, this.id)
        },
        onSelectionSrcChange(items) {
            this.selectedSrcItems = items
        },
        onRemoveUser(user) {
            this.$confirm(`<p>将用户：<strong>${user.name}</strong> 移出角色</p><p>是否继续?</p>`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
            }).then(() => {
                role_api.removeUsers(this.id, [user.id]).then(data => {
                    this.$message.success('移除成功')
                    this.onQueryDest(null, 3)
                }).catch(err => {
                    this.$message.error(err.message)
                })
            }).catch(err => {
            })
        },
        onAddUser(user) {
            role_api.addUsers(this.id, [user.id]).then(data => {
                this.$message.success('添加成功')
                this.onQuerySrc(null, 3)
                this.onQueryDest(null, 2)
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        onShowAddUser() {
            this.drawerSrc = true
        },
        moveup(node, id) {
            let arr = this.appDetailTree
            if (node.level > 1) {
                arr = node.parent.data.children
            }
            let idx = arr.findIndex(e => e.id == id)
            if (arr && idx > 0) {
                this.swapItem(arr, idx, idx - 1)
            }
        },
        movedown(node, id) {
            let arr = this.appDetailTree
            if (node.level > 1) {
                arr = node.parent.data.children
            }
            let idx = arr.findIndex(e => e.id == id)
            if (arr && idx < arr.length - 1) {
                this.swapItem(arr, idx, idx + 1)
            }
        },
        swapItem(arr, i, j) {
            let tmp = arr[i]
            arr[i] = arr[j]
            arr[j] = tmp
            this.rerenderFlag = false
            this.$nextTick(() => {
                this.rerenderFlag = true
                this.$nextTick(() => {
                    this.onResIdCheck()
                })
            })
        },
        applyProperties(dest, src) {
            for(let key in src){
                dest[key] = src[key]
            }
        },
    }
}
</script>

<style>
.scoped_1347 .up_down_icon_btn {
    padding: 2px!important;
}
.scoped_1347 .up_down_icon_btn {
    margin-left: 3px;
}
.scoped_1347 .el-tree-node {
    white-space: normal;
}
.scoped_1347 .el-tree-node__content {
    min-height: 26px;
    height: unset;
}
</style>